package com.example.springmac;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RestController
@RequestMapping("/session")
public class SessionController {
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Arrays.stream(cookies).forEach(ck->System.out.println(ck.getName()+":"+ck.getValue()));
        }
        return "获取cookie成功";
    }

    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite") String bite) {
        return "获取cookie成功, bite" + bite;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置session成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
}
